package com.hxgis.web.config;

import com.hxgis.common.utils.JsonUtil;
import com.hxgis.common.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Objects;


/*
 *  token校验
  * 系统访问控制类
 */
@Service
@Slf4j
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {



    /**
     * 设置允许跨域访问，并且进行token校验：
     * 1.判断是否是登录或退出请求，是直接放过
     * 2.不是则 获取请求头或url中的token值
     * 3.根据token 去redis中取用户信息 能取到放过，取不到属于非法访问
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //返回json
        response.setContentType("application/json;charset=UTF-8");
        //允许跨域
        response.setHeader("Access-Control-Allow-Origin","*");
        //允许写入的请求头
        response.setHeader("Access-Control-Allow-Headers",  "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");
        //允许的方法
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        //设置Access-Control-Max-Age来控制浏览器在多长时间内（单位s）无需在请求时发送预检请求
        //
        response.setHeader("Access-Control-Max-Age","1800");

        //login和logout 请求放过
        String url = request.getRequestURI();

        log.info("url :"+url);

        if (url.contains("/user/login") || url.contains("/user/logout")){
            return true;
        }

        //从请求头获取toekn
        String token = request.getHeader("Token");
        log.info("token------------------"+token);

        //判断用户是否在redis中
        if (Objects.nonNull(token)){
            return true;
        }


        //用户在redis中不存在，属于非法访问
        render(response,10001, "非法登陆");
        //先返回true
        return false;
    }

    private void render(HttpServletResponse response, Integer code, String messgae)throws Exception {
        OutputStream out = response.getOutputStream();
        String str  = JsonUtil.beanToString(ResultVOUtil.error(code, messgae));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }


}
